package com.sangeng.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.dto.AddRoleDto;
import com.sangeng.domain.dto.ChangeRoleDto;
import com.sangeng.domain.dto.UpdateRoleDto;
import com.sangeng.domain.entity.*;
import com.sangeng.domain.entity.Role;
import com.sangeng.domain.entity.Role;
import com.sangeng.domain.vo.RoleVo;
import com.sangeng.domain.vo.PageVo;
import com.sangeng.enums.AppHttpCodeEnum;
import com.sangeng.exception.SystemException;
import com.sangeng.mapper.RoleMapper;
import com.sangeng.mapper.RoleMenuMapper;
import com.sangeng.service.RoleMenuService;
import com.sangeng.service.RoleService;
import com.sangeng.utils.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 角色信息表(Role)表服务实现类
 *
 * @author makejava
 * @since 2022-08-19 19:53:27
 */
@Service("roleService")
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMapper roleMapper;
    private final RoleMenuService roleMenuService;

    @Override
    public List<String> selectRolesByUserId(long id) {
        //判断是否为管理员 如果是返回集合中只需要有admin
        if (id == 1L) {
            List<String> roleKeys = new ArrayList<>();
            roleKeys.add("admin");
            return roleKeys;
        }
        //否则 查询用户所具有的角色信息
        return getBaseMapper().selectRoleKeysByUserId(id);
    }

    @Override
    public ResponseResult<PageVo> getRoleList(Integer pageNum, Integer pageSize, String roleName, String status) {
        Page<Role> rolePage = new Page<>(pageNum, pageSize);
        //查询未被删除的role 由于设置了自动拼接del_flg查询，所以传入wrapper不用自己填
        //如果有角色名字和状态就要加入条件 “如果”：StringUtils.has
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(roleName), Role::getRoleName, roleName);
        wrapper.eq(StringUtils.hasText(status), Role::getStatus, status);
        wrapper.orderByAsc(Role::getRoleSort);

        Page<Role> page = page(rolePage, wrapper);
        List<Role> rolelist = page.getRecords();
        List<RoleVo> roleVoList = BeanCopyUtils.copyBeanList(rolelist, RoleVo.class);
        long total = page.getTotal();
        PageVo pageVo = new PageVo(roleVoList, total);
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult<String> changeRoleStatus(ChangeRoleDto changeRoleDto) {
        Role role = roleMapper.selectById(changeRoleDto.getRoleId());
        role.setStatus(changeRoleDto.getStatus());
        if (save(role)) {
            return ResponseResult.okResult();
        }
        throw new SystemException(AppHttpCodeEnum.ROLE_CHANGE_FAILED);
    }

    @Override
    public ResponseResult<String> deleteRoleById(List<Long> idList) {
        if (CollectionUtils.isNotEmpty(idList)) {
            boolean update = lambdaUpdate().set(Role::getDelFlag, 1).in(Role::getId, idList).update();
            return update ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.ROLE_DELETE_ERROR);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_ERROR);
    }

    @Override
    public ResponseResult<String> addRole(AddRoleDto roleDto) {
        Role role = BeanCopyUtils.copyBean(roleDto, Role.class);
        if (Objects.isNull(roleDto.getMenuIds()) && roleDto.getMenuIds().length > 0){
            insertRoleMenu(roleDto, role);
        }
        save(role);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<String> updateRole(UpdateRoleDto roleDto) {
        Role role = BeanCopyUtils.copyBean(roleDto, Role.class);
        boolean update = updateById(role);
        if (update) {
            return ResponseResult.okResult();
        } else {
            throw new SystemException(AppHttpCodeEnum.ROLE_UPDATE_ERROR);
        }
    }

    private void insertRoleMenu(AddRoleDto roleDto, Role role) {
        List<RoleMenu> roleMenuList = Arrays.stream(roleDto.getMenuIds())
                .map(memuId -> new RoleMenu(role.getId(), memuId))
                .collect(Collectors.toList());
        roleMenuService.saveBatch(roleMenuList);
    }
}

